import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios'

export const fetchHomeMultidataAction = createAsyncThunk(
  'fetch/homemultidate',
  // 通过homeSlice中的extraReducers配置一起操作，需要返回res.data数据结构
  async () => {
    const res = await axios.get('http://123.207.32.32:8000/home/multidata')
    return res.data
  }

  // 第二种写法（直接调用相关action操作）
  /* async (extreInfo, { dispatch, getState }) => {
    console.log(extreInfo, dispatch, getState)
    const res = await axios.get('http://123.207.32.32:8000/home/multidata')
    dispatch(changeBanners(res.data.data.banner.list))
    dispatch(changeRecommends(res.data.data.recommend.list))
  } */
)

const homeSlice = createSlice({
  name: 'home',
  initialState: {
    banners: [],
    recommends: [],
  },
  reducers: {
    changeBanners(state, { payload }) {
      state.banners = payload
    },
    changeRecommends(state, { payload }) {
      state.recommends = payload
    },
  },
  // 第一种extraReducers
  extraReducers: {
    [fetchHomeMultidataAction.pending](state, action) {
      console.log('fetchHomeMultidataAction pending', state, action)
    },
    [fetchHomeMultidataAction.fulfilled](state, { payload }) {
      console.log('fetchHomeMultidataAction fulfilled', payload)
      state.banners = payload.data.banner.list
      state.recommends = payload.data.recommend.list
    },
    [fetchHomeMultidataAction.rejected](state, action) {
      console.log('fetchHomeMultidataAction rejected', state, action)
    },
  },

  // 第二种extraReducers
  /* extraReducers: (builder) => {
    builder
      .addCase(fetchHomeMultidataAction.pending, (state, { payload }) => {
        console.log('fetchHomeMultidataAction pending', state, payload)
      })
      .addCase(fetchHomeMultidataAction.fulfilled, (state, { payload }) => {
        console.log('fetchHomeMultidataAction fulfilled', payload)
        state.banners = payload.data.banner.list
        state.recommends = payload.data.recommend.list
      })
      .addCase(fetchHomeMultidataAction.rejected, (state, { payload }) => {
        console.log('fetchHomeMultidataAction rejected', state, payload)
      })
  }, */
})

export const { changeBanners, changeRecommends } = homeSlice.actions
export default homeSlice.reducer
